package com.shangma.cn.controller;

import com.shangma.cn.commons.http.AxiosResult;
import com.shangma.cn.commons.http.AxiosStatus;
import com.shangma.cn.commons.upload.UploadUtils;
import com.shangma.cn.commons.utils.CacheUtils;
import com.shangma.cn.commons.utils.CodeUtils;
import com.shangma.cn.commons.utils.TokenService;
import com.shangma.cn.commons.utils.TreeUtils;
import com.shangma.cn.dto.base.impl.MenuDTO;
import com.shangma.cn.entity.LoginAdmin;
import com.shangma.cn.entity.base.impl.Admin;
import com.shangma.cn.entity.base.impl.AdminRole;
import com.shangma.cn.entity.base.impl.Menu;
import com.shangma.cn.exception.base.impl.ApiException;
import com.shangma.cn.exception.base.impl.UploadException;
import com.shangma.cn.service.AdminService;
import com.shangma.cn.service.MenuService;
import com.shangma.cn.service.RoleService;
import com.shangma.cn.transfer.base.impl.MenuTransfer;
import com.wf.captcha.GifCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Part;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 开发人员: 辉哥真球帅
 * 联系方式: zhengzhoudaxuevip@163.com
 * 创建时间: 2021/10/7  16:49
 * 文件含义:
 */
@RestController
@RequestMapping("common")
public class CommonController {


    /**
     * 1: 必须是jgp  png  jpeg 格式
     * <p>
     * 2：必须宽100 高100
     * <p>
     * 3：100K以内
     * <p>
     * <p>
     * <p>
     * //////////////////////////////////////////////////////////
     * <p>
     * 把表格数据导入到数据库中
     * <p>
     * 上传表格
     *
     * @param avatar
     * @return
     * @throws Exception
     */
    @PostMapping("upload")
    public AxiosResult<String> upload(@RequestPart Part avatar) throws Exception {
        //必须的是个图片
        BufferedImage read = ImageIO.read(avatar.getInputStream());
        if (read == null)
            throw new UploadException(AxiosStatus.NOT_IS_IMG);
        String ext = StringUtils.getFilenameExtension(avatar.getSubmittedFileName());
        if (!("jpg").equalsIgnoreCase(ext) && !"png".equalsIgnoreCase(ext))
            throw new UploadException(AxiosStatus.IMG_EXT_NOT_RIGHT);
        if (read.getHeight() != 100 || read.getWidth() != 100)
            throw new UploadException(AxiosStatus.IMG_LENGTH_ERROR);
        if (avatar.getSize() / 1024 > 100)
            throw new UploadException(AxiosStatus.IMG_SIZE_ERROR);
        String filename = UUID.randomUUID().toString() + "." + ext;
        String upload = UploadUtils.upload(filename, avatar.getInputStream());
        return AxiosResult.success(upload);
    }


    /**
     * 获取验证码
     * 手机号
     * 邮箱
     */


    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @GetMapping("getCode")
    public AxiosResult<String> getLoginCode(String uuid) {
        //返回前端一个验证码的图片
        GifCaptcha gifCaptcha = new GifCaptcha(130, 32, 6);
        //值
        String text = gifCaptcha.text();
        CodeUtils.setCodeCache(uuid, text);
        return AxiosResult.success(gifCaptcha.toBase64());
    }


    /**
     * 登录操作
     */


    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MenuTransfer menuTransfer;
    @Autowired
    private MenuService menuService;

    @PostMapping("doLogin")
    public AxiosResult<String> doLogin(@RequestBody Map<String, String> map) {
        String uuid = map.get("uuid").toString();
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        String code = map.get("code").toString();
        //判断验证码 
        String s = CodeUtils.getCodeCache(uuid);
        if (StringUtils.isEmpty(s) || !s.equalsIgnoreCase(code)) {
            //验证码错误
            throw new ApiException(AxiosStatus.CODE_ERROR);
        }
        //通过用户名查询用户
        Admin admin = adminService.findAdminByUsername(username);
        if (admin == null) {
            throw new ApiException(AxiosStatus.ACCOUNT_ERROR);
        }
        //比较密码
        boolean matches = bCryptPasswordEncoder.matches(password, admin.getAccountPwd());
        if (!matches) {
            //密码错误
            throw new ApiException(AxiosStatus.PASSWORD_ERROR);
        }
        CodeUtils.deleteCodeCache(uuid);
        //登录成功
        // 缓存登录用户和返回Token
        return AxiosResult.success(tokenService.cacheLoginAdminAndCreateToken(admin));
    }

    /**
     * 获取用户的动态菜单
     */


    @GetMapping("getAdminInfo")
    public AxiosResult<Map<String, Object>> getAdminInfo() {
        Map<String, Object> map = new HashMap<>();
        LoginAdmin cacheLoginAdmin = tokenService.getCacheLoginAdmin();
        boolean admin = cacheLoginAdmin.getAdmin().isAdmin();
        if (admin) {
            //
            System.out.println("我是超级管理员");
            List<Menu> list = menuService.list();
            //(菜单 包含目录和菜单）
            List<Menu> collect = list.stream().filter(menu -> menu.getMenuType() != 2).collect(Collectors.toList());
            List<Menu> btnMenus = list.stream().filter(menu -> menu.getMenuType() != 0).collect(Collectors.toList());
            //把登录用户的按钮级别权限放到Redis中
            cacheLoginAdmin.setMenuList(btnMenus);
            tokenService.setLoginAdminCache(cacheLoginAdmin);


            List<Menu> rootMenus = collect.stream().filter(menu -> menu.getParentId().equals(0L)).collect(Collectors.toList());
            collect.removeAll(rootMenus);
            List<MenuDTO> rootDTOS = menuTransfer.toDTOS(rootMenus);
            List<MenuDTO> collectDTOS = menuTransfer.toDTOS(collect);
            TreeUtils.buildTreeData(rootDTOS, collectDTOS);
            map.put("menus", rootDTOS);
            map.put("btn",btnMenus);

        } else {
            System.out.println("我不是超级管理员");
            LoginAdmin loginAdmin = tokenService.getCacheLoginAdmin();
            //查询用户的角色
            List<Long> roleIds = adminService.getAdminAndRolesById(loginAdmin.getAdmin().getId()).getRoleIds();
            //通过角色查询权限(所有权限)
            List<Menu> allMenus = roleService.getMenusByRoleId(roleIds);
            //按钮干掉就是菜单 （菜单 包含目录和菜单）
            List<Menu> collect = allMenus.stream().filter(menu -> menu.getMenuType() != 2).collect(Collectors.toList());
            List<Menu> btnMenus = allMenus.stream().filter(menu -> menu.getMenuType() != 0).collect(Collectors.toList());
            loginAdmin.setMenuList(btnMenus);
            tokenService.setLoginAdminCache(loginAdmin);
            List<Menu> rootMenus = collect.stream().filter(menu -> menu.getParentId().equals(0L)).collect(Collectors.toList());
            collect.removeAll(rootMenus);
            List<MenuDTO> rootDTos = menuTransfer.toDTOS(rootMenus);
            List<MenuDTO> menuDTOS = menuTransfer.toDTOS(collect);
            TreeUtils.buildTreeData(rootDTos, menuDTOS);
            map.put("menus", rootDTos);
            map.put("btn",btnMenus);
        }

        return AxiosResult.success(map);

    }

}
